/*
 * Copyright (c) 2015 Hannes Dorfmann.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.cocolover2.andbase.adapterdelegates;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;

import com.cocolover2.andbase.utils.MLogger;

import java.util.List;


public class BaseDelegationAdapter<T extends List<?>> extends RecyclerView.Adapter {

    protected AdapterDelegatesManager<T> delegatesManager;
    protected T items;

    public BaseDelegationAdapter(T items) {
        this(new AdapterDelegatesManager<T>());
        this.items = items;
    }

    public BaseDelegationAdapter(AdapterDelegatesManager<T> delegatesManager) {
        if (delegatesManager == null) {
            throw new NullPointerException("AdapterDelegatesManager2 is null");
        }

        this.delegatesManager = delegatesManager;
    }

    public AdapterDelegatesManager<T> getAdapterDelegatesManager() {
        return delegatesManager;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return delegatesManager.onCreateViewHolder(parent, viewType);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        delegatesManager.onBindViewHolder(items, position, holder);
    }

    @Override
    public int getItemViewType(int position) {
        return delegatesManager.getItemViewType(items, position);
    }

    @Override
    public int getItemCount() {
        return items == null ? 0 : items.size();
    }

    public T getItems() {
        return items;
    }

    public void addDelegate(@NonNull AdapterDelegate<T> delegate) {
        delegatesManager.addDelegate(delegate);
    }

    /**
     * 移除item
     *
     * 防止直接调用notifyItemRemoved造成的角标越界bug<br>
     * 1.这里虽然重新刷新布局但还是和{@link RecyclerView.Adapter#notifyDataSetChanged()}有区别
     *
     * @param position
     * @since 1.1.1
     */
    public void removeItem(int position) {
        items.remove(position);
        notifyItemRemoved(position);
        // 这个判断的意义就是如果移除的是最后一个
        if (position != items.size()) {
            notifyItemRangeChanged(position, items.size() - position);
        }
    }
}
